package edu.office.applicationRepository;


import edu.office.entities.Roleinfo;
import edu.office.entities.User;
import edu.office.tools.StaticFields;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.servlet.http.HttpSession;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;

/**
 *
 * @author hgs
 */
@Named("mySystemRepositoryA")
@ApplicationScoped
public class MySystemRepository implements Serializable{

    @Inject
    RoleinfoRepository roleinfoRepository;
    @Inject
     RoleinfoRepository applicationRoleinfoRepository;
    private HashMap<Roleinfo, HashSet<HttpSession>> sessionmap = new HashMap<>();
    private HashMap<Roleinfo, HashSet<User>> usersmap = new HashMap<>();

    @PostConstruct
    public void init() {
        sessionmap.put(applicationRoleinfoRepository.getTeacherRoleinfo(), new HashSet<>());
        sessionmap.put(applicationRoleinfoRepository.getStudentRoleinfo(), new HashSet<>());
        sessionmap.put(applicationRoleinfoRepository.getReexaminRoleinfo(), new HashSet<>());
        usersmap.put(applicationRoleinfoRepository.getTeacherRoleinfo(), new HashSet<>());
        usersmap.put(applicationRoleinfoRepository.getStudentRoleinfo(), new HashSet<>());
        usersmap.put(applicationRoleinfoRepository.getReexaminRoleinfo(), new HashSet<>());
    }

    public HashMap<Roleinfo, HashSet<HttpSession>> getSessionMap() {
        return sessionmap;
    }

    public void setSessionMap(HashMap<Roleinfo, HashSet<HttpSession>> sessionmap) {
        this.sessionmap = sessionmap;
    }

    public HashSet<User> getLogingedTeacher() {
        usersmap.get(applicationRoleinfoRepository.getTeacherRoleinfo()).clear();
        for (HttpSession session : getSessionMap().get(applicationRoleinfoRepository.getTeacherRoleinfo())) {
            if (null != session) {
                usersmap.get(applicationRoleinfoRepository.getTeacherRoleinfo()).add((User) session.getAttribute(StaticFields.SESSION_MYUSER));
            }
        }
        return usersmap.get(applicationRoleinfoRepository.getTeacherRoleinfo());
    }

    public HashSet<User> getLoginedStudent() {
        usersmap.get(applicationRoleinfoRepository.getStudentRoleinfo()).clear();
        for (HttpSession session : getSessionMap().get(applicationRoleinfoRepository.getStudentRoleinfo())) {
            if (null != session && null != session.getId()) {
                try {
                    usersmap.get(applicationRoleinfoRepository.getStudentRoleinfo()).add((User) session.getAttribute(StaticFields.SESSION_MYUSER));
                } catch (Exception e) {
                    System.out.println("getLoginedStudent");
                }
            }
        }
        return usersmap.get(applicationRoleinfoRepository.getStudentRoleinfo());
    }

}
